#!/usr/bin/env bash
# DESCRIPTION
#     Extracts the gacha URL from the Chromium Embedded Framework cache.
#     The file paths are detected automatically based on the game process ID
#     and executable path.
#
# NOTES
#     This script currently returns the last URL in the cache file, which
#     usually works but is not entirely reliable.
#
# EXIT STATUS
#     0 on success

set -e
GIPATH="."

function get_path_from_pid() {
	# tee eats the status value
	_pid=$(pgrep -f -- "GenshinImpact.exe" | tee | head -1)
	if [ -z "$_pid" ]; then
		_pid=$(pgrep -f -- "YuanShen.exe" | tee | head -1)
	fi
	[ -z "$_pid" ] && echo "Game process not found" && exit 1
	GIPATH=$(pwdx "$_pid")
	GIPATH=${GIPATH#*\ } # remove leading "pid: "
}

get_path_from_pid

# Get the most recently modified "data_2" file: ISO timestamp + absolute path
CACHEFILE=$(find "$GIPATH" -type f -wholename '*/Cache_Data/data_2' -printf "%T+ %p\n" | sort | tail -n 1)
CACHEFILE=${CACHEFILE#*\ } # remove leading timestamp
echo "Found cache file: $CACHEFILE"
echo "===== Matching links:"

strings "$CACHEFILE" | grep -o "https://.*/e20190909gacha-v3/.*" | tail -n1
